﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;

namespace Activity.Redis.Helper
{
    public static class ConfigurationHelper
    {
        private static Configuration _config;
        static Configuration Config
        {
            get
            {
                return _config ??
                       (_config = WebConfigurationManager.OpenWebConfiguration("/"));
            }
        }
        /// <summary>
        /// 从Web.config中读取设置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="page"></param>
        /// <param name="pKey"></param>
        /// <param name="dv"></param>
        /// <returns></returns>
        public static T GetConfiguration<T>(this Page page, string pKey, T dv)
        {
            return Get(pKey, dv);
        }
        /// <summary>
        /// 从Web.config中读取设置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="page"></param>
        /// <param name="pKey"></param>
        /// <returns></returns>
        public static T GetConfiguration<T>(this Page page, string pKey)
        {
            return Get<T>(pKey);
        }
        /// <summary>
        /// 从Web.config中读取设置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="httpHandler"></param>
        /// <param name="pKey"></param>
        /// <param name="dv"></param>
        /// <returns></returns>
        public static T GetConfiguration<T>(this IHttpHandler httpHandler, string pKey, T dv)
        {
            return Get(pKey, dv);
        }
        /// <summary>
        /// 从Web.config中读取设置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="httpHandler"></param>
        /// <param name="pKey"></param>
        /// <returns></returns>
        public static T GetConfiguration<T>(this IHttpHandler httpHandler, string pKey)
        {
            return Get<T>(pKey);
        }
        /// <summary>
        /// 从Web.config中读取设置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pKey"></param>
        /// <returns></returns>
        public static T Get<T>(string pKey)
        {
            if (!WebConfigurationManager.AppSettings.AllKeys.Contains(pKey))
            {
                return default(T);
            }
            var data = WebConfigurationManager.AppSettings[pKey];
            var converter = TypeDescriptor.GetConverter(typeof(T));
            if (converter.CanConvertFrom(typeof(string)))
            {
                var o = converter.ConvertFrom(data);
                if (o != null) return (T)o;
            }
            return default(T);
        }

        public static void Set(string pKey, decimal pValue)
        {
            Set(pKey, pValue.ToString());
        }
        public static void Set(string pKey, int pValue)
        {
            Set(pKey, pValue.ToString());
        }
        public static void Set(string pKey, bool pValue)
        {
            Set(pKey, pValue.ToString());
        }

        public static void Set(string pKey, string pValue)
        {
            if (Config.AppSettings.Settings.AllKeys.Contains(pKey))
            {
                Config.AppSettings.Settings.Remove(pKey);
            }
            Config.AppSettings.Settings.Add(pKey, pValue);
            Config.Save();
        }
        /// <summary>
        /// 如果值已经存在就不做任何处理
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        private static void CreateKey(string key, string value)
        {
            lock ("Web.config:AppSettings:" + key)
            {
                //判断是否已经存在
                if (Config.AppSettings.Settings.AllKeys.Contains(key)) return;
                Config.AppSettings.Settings.Add(key, value);
                try
                {
                    Config.Save();
                }
                catch (Exception)
                {
                }
            }
        }
        /// <summary>
        /// 从Web.config中读取设置
        /// </summary>
        /// <typeparam name="T">可以从string转换的类型</typeparam>
        /// <param name="pKey"></param>
        /// <param name="dv">
        /// 如果 该设置项不存在会返回这个默认值，并且把这个值写到web.confg中去
        /// </param>
        /// <returns></returns>
        public static T Get<T>(string pKey, T dv)
        {
            if (!WebConfigurationManager.AppSettings.AllKeys.Contains(pKey))
            {
                CreateKey(pKey, dv.ToString());
                return dv;
            }
            var data = WebConfigurationManager.AppSettings[pKey];
            var converter = TypeDescriptor.GetConverter(typeof(T));
            if (converter.CanConvertFrom(typeof(string)))
            {
                var o = converter.ConvertFrom(data);
                if (o != null) return (T)o;
            }
            return dv;
        }
        /// <summary>
        /// 从Web.config中读取设置（int）
        /// </summary>
        /// <param name="pKey"></param>
        /// <param name="dv"></param>
        /// <returns></returns>
        public static int Get(string pKey, int dv = 0)
        {
            if (WebConfigurationManager.AppSettings.AllKeys.Contains(pKey))
            {
                int.TryParse(WebConfigurationManager.AppSettings[pKey], out dv);
            }
            else
            {
                CreateKey(pKey, dv.ToString());
            }
            return dv;
        }
        /// <summary>
        /// 从Web.config中读取设置（bool）
        /// </summary>
        /// <param name="pKey"></param>
        /// <param name="dv"></param>
        /// <returns></returns>
        public static bool Get(string pKey, bool dv = false)
        {
            if (WebConfigurationManager.AppSettings.AllKeys.Contains(pKey))
            {
                bool.TryParse(WebConfigurationManager.AppSettings[pKey], out dv);
            }
            else
            {
                CreateKey(pKey, dv.ToString());
            }
            return dv;
        }
        /// <summary>
        /// 从Web.config中读取日期类型设置项
        /// </summary>
        /// <param name="pKey"></param>
        /// <param name="dv"></param>
        /// <returns></returns>
        public static DateTime Get(string pKey, DateTime dv)
        {
            if (WebConfigurationManager.AppSettings.AllKeys.Contains(pKey))
            {
                DateTime.TryParse(WebConfigurationManager.AppSettings[pKey], out dv);
            }
            else
            {
                CreateKey(pKey, dv.ToString());
            }
            return dv;
        }
    }
}
